package com.gitee.leijin.rbac.exception;

import com.gitee.leijin.rbac.enums.CodeEnum;
import com.gitee.leijin.rbac.util.Result;
import lombok.extern.slf4j.Slf4j;

import org.springframework.dao.DuplicateKeyException;
import org.springframework.http.HttpStatus;
import org.springframework.jdbc.BadSqlGrammarException;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;


@RestControllerAdvice
// 统一设置http状态码为200，只通过业务code区分请求成功失败，也避免axios走到onRejected的回调
@ResponseStatus(HttpStatus.OK)
@Slf4j
public class MvcExHandler {


    /**
     * 处理 BindException
     *  application/x-www-form-urlencoded
     */
    @ExceptionHandler(BindException.class)
    public Result<String> handleBindException(BindException e) {
        log.error("参数绑定异常", e);
        List<FieldError> fieldErrors = e.getFieldErrors();
        return Result.failure(buildErrorMsg(fieldErrors));
    }

    /**
     * 处理 MethodArgumentNotValidException
     *  application/json + 后台使用RequestBody
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result<String> handleBindException(MethodArgumentNotValidException e) {
        log.error("入参校验失败", e);
        BindingResult bindingResult = e.getBindingResult();
        List<FieldError> fieldErrors = bindingResult.getFieldErrors();
        return Result.failure(buildErrorMsg(fieldErrors));
    }

    /**
     * 注解 @Validated写在类上 + 入参带有jsr303注解校验出错
     */
    @ExceptionHandler(ConstraintViolationException.class)
    public Result<String> handleBindException(ConstraintViolationException e) {
        log.error("参数校验异常", e);
        Set<ConstraintViolation<?>> violations = e.getConstraintViolations();
        String errorMsg = violations.stream().map(v -> "属性:" + v.getPropertyPath() + "，值:" + v.getInvalidValue() + ", 校验不通过，原因:" + v.getMessage())
                .collect(Collectors.joining(";"));
        return Result.failure(errorMsg);
    }

    @ExceptionHandler(IllegalArgumentException.class)
    public Result<String> handleBindException(IllegalArgumentException e) {
        log.error("参数非法", e);
        return Result.failure(CodeEnum.PARAM_ERR);
    }

    @ExceptionHandler(BadSqlGrammarException.class)
    public Result<String> handleBindException(BadSqlGrammarException e) {
        log.error("数据库访问异常", e);
        return Result.failure(e.getMessage());
    }

    @ExceptionHandler(DuplicateKeyException.class)
    public Result<String> handleBindException(DuplicateKeyException e) {
        log.error("唯一约束校验失败", e);
        return Result.failure(e.getMessage());
    }

    @ExceptionHandler(BizException.class)
    public Result<String> handleBindException(BizException e) {
        log.error("业务异常", e);
        return Result.failure(e.getCode(), e.getMessage());
    }

    @ExceptionHandler(Exception.class)
    public Result<String> handleBindException(Exception e) {
        log.error("系统未知异常", e);
        return Result.failure(CodeEnum.SYS_ERR.getCode(), e.getMessage());
    }

    private String buildErrorMsg(List<FieldError> fieldErrors) {
        return fieldErrors.stream()
                .map(v -> "属性:" + v.getField() + ",值:" + v.getRejectedValue() + ", 校验不通过，原因:" + v.getDefaultMessage())
                .collect(Collectors.joining(";"));
    }
}
